#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/4/30 9:55
# @Author  : Link
# @Site    : 
# @File    : app.py
# @Software: PyCharm

from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView

from .src import src_ui
from .component.main_ui import Main_Ui
from .component.web_view_widget import MyQWebEngineView


class Main(Main_Ui):

    def __init__(self, channel_obj=None, channel=None, view=None):
        super(Main, self).__init__()
        # table 信号和槽
        if channel_obj is None or channel is None:
            raise ValueError("channel_obj must not none")
        self.channel_obj = channel_obj
        self.channel = channel
        # 初始化
        self.channel_obj.append_status_message.connect(self.append_message)
        # myObj.show_status_message.connect(self.show_message)
        self.channel_obj.message.connect(self.message_show)

        if view is None:
            self.main_view_factory()
        else:
            self.other_view_factory(view)

    def web_view_factory(self, url="https://www.baidu.com/"):
        web_view = MyQWebEngineView()
        web_view.load(QUrl(url))
        self.insert(web_view=web_view)

    def main_view_factory(self):
        """
        启动后 生成一个主Tab
        :return:
        """
        web_view = MyQWebEngineView()
        web_view.load(QUrl('qrc:/index.html'))
        # web_view.load(QUrl('http://localhost:9528/'))
        web_view.page().setWebChannel(self.channel)
        self.insert(web_view=web_view)

    def other_view_factory(self, event: QWebEngineView):
        # 添加新Tab
        event.page().setWebChannel(self.channel)
        self.insert(web_view=event)

    def create_window_browser(self, event: QWebEngineView):
        self.new_win = Main(self.channel_obj, self.channel, event)
        self.new_win.show()

    def insert(self, title='new web window', web_view=None):
        if web_view is None:
            view = self.main_view_factory()
        else:
            view = web_view

        self.view_tables.append(view)
        widget = self.view_tables[-1]
        self.view_tables_ids.append(id(widget))

        # widget.link_pyqtSignal.connect(self.test)
        widget.title_pyqtSignal.connect(self.change_table_title)
        widget.new_view_pyqtSignal.connect(self.other_view_factory)
        widget.new_window_pyqtSignal.connect(self.create_window_browser)

        self.horizontalSlider.valueChanged.connect(widget.set_zoom_factor)

        self.table.addTab(widget, title)
        if self.view_last_table:
            self.table.setCurrentIndex(self.table.count() - 1)

    def test(self, *args):
        print(args)

    def change_table_title(self, id, title):
        """
        通过传来的信号的widget id去找index
        :param id:
        :param title:
        :return:
        """
        table_index = self.view_tables_ids.index(id)
        self.table.setTabText(table_index, title)
